<template>
  <div class="app-container">
    <div class="invitation-filterhead">
      <el-form :inline="true" :model="form" ref="form">
        <el-form-item label="活动名称：" prop="name">
          <el-input
            placeholder="请输入活动名称"
            prefix-icon="el-icon-search"
            v-model="form.name">
          </el-input>
        </el-form-item>
        <el-form-item label="创建时间：" prop="time">
          <el-date-picker
            value-format="yyyy-MM-dd"
            v-model="form.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">筛选</el-button>
          <el-button @click="onCancel()">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-box">
      <el-button type="primary" class="add-activity" @click="showBigBoxFn()">创建任务</el-button>
      <el-table :data="tableData" v-loading="tableLoading">
      <el-table-column label="序号" type="index" :index="indexMethod" />
      <el-table-column prop="id" label="任务ID" />
      <el-table-column prop="name" label="任务名称" />
      <el-table-column prop="sendDate" label="发送时间" />
      <el-table-column prop="operatorName" label="创建人" />
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <!-- 活动状态   待开始 进行中 已结束	 -->
          <span>{{ statusConfig[+scope.row.status] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <!-- 启动传1  关闭传4 -->
          <el-switch
            class="table-switch"
            :value="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="($event) => changeSwitch($event, scope.row)"          >
          </el-switch>
          <el-button @click="viewDetails(scope.row)" type="text" size="small">查看</el-button>
          <el-button @click="editDetails(scope.row)" type="text" size="small" v-if="scope.row.status === 0">编辑</el-button>
          <el-button class="disable-edit" type="text" size="small" v-else>编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>
    <!-- 新建 -->
    <el-dialog title="配置页" :visible.sync="bigBoxStatus" width="1100px" :before-close="bigBoxStatusBefore" destroy-on-close>
      <el-form :model="form2" ref="form2" label-position="right" label-width="100px" :rules="rules">
        <el-form-item label="任务名称" prop="name">
          <el-input
            placeholder="请输入任务名称"
            maxlength="20"
            prefix-icon="el-icon-search"
            v-model="form2.name">
          </el-input>
        </el-form-item>
        <el-form-item label="选择模版" prop="templateId">
          <el-select v-model="form2.templateId" placeholder="请选择模版">
            <el-option
              v-for="item in mobanoptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="任务周期" prop="templateId">
          <el-select v-model="form2.sendType" filterable placeholder="请选择任务周期" :disabled="editStatus">
            <el-option
              v-for="item in sendTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="模版配置" v-if="form2.templateId === '2'">
          <div class="sms_moban_config">
            petiboxy的顾客您好，新年将至，受物流公司运营时间影响，
            <el-form-item prop="time">
              <el-input
                placeholder="请输入"
                v-model="form2.time">
              </el-input>
            </el-form-item>后的订单我们将统一于
            <el-form-item prop="time1">
              <el-input
              placeholder="请输入"
              v-model="form2.time1">
            </el-input>
            </el-form-item>开始陆续发货，感谢您的理解!
          </div>
        </el-form-item>
        <el-form-item label="发送时间" prop="sendDate">
          <el-date-picker
            v-model="form2.sendDate"
            type="datetime"
            placeholder="选择日期时间"
            :picker-options="{ disabledDate }"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发放人群" prop="targetType">
          <el-select v-model="form2.targetType" placeholder="发放人群">
            <el-option label="标签人群" value="1" />
            <el-option label="特定人群" value="3" />
            <el-option label="自定义人群" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签人群" prop="userTagId" v-if="form2.targetType === '1'">
          <el-select v-model="form2.userTagId" placeholder="标签人群">
            <el-option v-for="item in userTagList" :key="item.id" :label="item.tagName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="特定人群" prop="specificUserType" v-if="form2.targetType === '3'">
          <el-select v-model="form2.specificUserType" placeholder="特定人群">
            <el-option v-for="item in userTypeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义人群" prop="userIds" v-if="form2.targetType === '2'" style="margin-bottom: 0;">
        <el-input type="textarea" :rows="4" v-model="form2.userIds" placeholder="自定义人群(多个uid，换行隔开)" />
        </el-form-item>
        <el-form-item label=" " v-if="form2.targetType === '2'">
          <div class="upload-container">
            <label for="file-upload" class="custom-upload-button">
              <i class="el-icon-upload2"></i> 选择文件
            </label>
            <input type="file" id="file-upload" style="display: none;" @change="changeFile">
            <!-- <p id="file-name"></p> -->
          </div>
        </el-form-item>
        <div class="submint-btn">
          <el-form-item>
              <el-button
                type="primary"
                @click="onEditSubmit('form2')"
                v-loading.fullscreen.lock="bigBoxLoading"
              >
                提交
              </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
    <!-- 查看 -->
    <el-dialog title="短信详情" :visible.sync="bigBoxViewStatus" fullscreen>
      <el-form label-position="right" label-width="100px">
        <el-form-item label="任务名称">
          {{ detail.name }}
        </el-form-item>
        <el-form-item label="文案">
          {{ detail.content }}
        </el-form-item>
        <el-form-item label="发送时间">
          {{ detail.sendDate }}
        </el-form-item>
        <el-form-item label="发送人群">
          {{ detail.targetType === 1 ? detail.userTagId : detail.targetType === 3 ? userTypeList[+detail.specificUserType - 1].label : '自定义人群' }}
        </el-form-item>
        <el-form-item label="编辑记录">
          <!-- {{ detail.records }} -->
          <el-table :data="detail.records">
            <el-table-column prop="operUserName" label="编辑人" />
            <el-table-column prop="createdTime" label="编辑时间" />
          </el-table>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog title="编辑短信发送时间" width="30%" :visible.sync="editBoxStatus" destroy-on-close>
      <el-form :model="editForm" ref="editForm" label-position="right" :rules="editRules">
        <el-form-item label="发送时间" prop="sendDate">
          <el-date-picker
            v-model="editForm.sendDate"
            type="datetime"
            placeholder="选择日期时间"
            :picker-options="{ disabledDate }"
          >
          </el-date-picker>
        </el-form-item>
        <div class="submint-btn">
          <el-form-item>
            <el-button
              type="primary"
              @click="onEditSubmit('editForm')"
            >
              提交
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { ref } from "vue";
import { mapGetters } from "vuex";
import {
  queryTemplateList,
  queryManageList,
  getManage,
  addSms,
  updateManageStatus,
  updateManage
} from '@/api/sms/template';
import {
  userRelList
} from '@/api/user/user';
import { userTypeList } from '@/constants/sms';

import { inviteUserType } from '@/constants/inviteCampaign';
import { numberToChinese } from '@/utils/numberToChinese';
import moment from 'moment';
export default {
  name: '/sms/index',
  computed: {
    ...mapGetters(['sms']),
  },
  data() {
    return {
      numberToChinese,
      activityNameInput: '',
      pickerValue: '',
      tableData: [],
      tableLoading: false,
      bigBoxLoading: false,
      form: {
        name: '',
        time: ''
      },
      mobanoptions: [],
      statusConfig: ['无效', '有效'],
      bigBoxStatus: false, // 创建新活动、编辑活动、查看活动 大弹框展示与否
      bigBoxViewStatus: false, // 查看活动
      form2: {
        name: '',
        templateId: '', // 模版id
        sendDate: '',
        time: '',
        time1: '',
        targetType: undefined,
        userTagId: [],
        userIds: undefined,
        specificUserType: undefined,
      },
      rules:{
        name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        templateId: [{ required: true, message: '请选择模版', trigger: 'blur' }],
        sendDate: [{ required: true, message: '请选择发送时间', trigger: 'blur' }],
        time: [{ required: true, message: '请输入短信配置信息', trigger: 'blur' }],
        time1: [{ required: true, message: '请输入短信配置信息', trigger: 'blur' }],
        targetType: [{ required: true, message: '请选择目标人群', trigger: 'blur' }],
        userTagId: [{ required: true, message: '请选择用户标签', trigger: 'blur' }],
        userIds: [{ required: true, message: '请设置目标人群', trigger: 'blur' }],
        specificUserType: [{ required: true, message: '请选择特定人群', trigger: 'blur' }],
      },
      selectDataInfo: {}, // 选中的数据
      userTagList: [],
      userTypeList,
      detail: '', // 详情
      editBoxStatus: false,
      editForm: { // 禁用状态下可以编辑发送时间
        sendDate: ''
      },
      editRules:{
        sendDate: [{ required: true, message: '请选择发送时间', trigger: 'blur' }],
      },
      editStatus: false,
    }
  },
  mounted() {
    this.getTableData()
  },
  methods: {
    getTemplateList() {
      queryTemplateList({}).then(res => {
        if (res.code === 200) {
          this.mobanoptions = res.data
          console.log('res.rows', res)
        }
      })
    },
    getTableData() {
      this.tableLoading = true
      queryManageList({
        name: this.form.name,
        createdStartTime: this.form.time !== '' ? this.form.time[0] : '',
        createdEndTime: this.form.time !== '' ? this.form.time[1] : '',
      }).then(res => {
        if (res.code === 200) {
          console.log('res.rows', res.rows)
          this.tableData = res.rows
        }
        this.tableLoading = false
      })
    },
    bigBoxStatusBefore() {
      this.resetForm('form2');
      // this.editStatus = false;
      this.bigBoxStatus = false;
    },
    indexMethod(index) {
      return index + 1;
    },
    onSubmit() {
      this.getTableData()
    },
    onCancel() {
      this.$refs['form'].resetFields();
      this.getTableData()
    },
    changeSwitch(value, item) {
      console.log('changeSwitch', value)
      updateManageStatus({
        id: item.id,
        status: value ? 1 : 0
      }).then(res => {
        if (res.code === 200) {
          console.log('res.rows', res.rows)
          this.getTableData()
        }
        this.tableLoading = false
      })
    },
    viewDetails(record) {
      // console.log(record)
    //  this.getManageApiFn(record, 'view');
    this.$router.push({path: '/sms/detail', query: { id: record.id }})
    },
    editDetails(record) {
      this.selectDataInfo = record;
      this.getManageApiFn(record, 'edit');
    },
    getManageApiFn(record, type) {
      getManage({
        id: record.id
      }).then(res => {
        if (res.code === 200) {
          if(type === 'view') this.detail = res.data;
          if(type === 'edit') {
            this.editForm.sendDate = res.data.sendDate;
            this.editBoxStatus = true;
            // this.editStatus = true;
            // this.form2 = {
            //   name: res.data.name,
            //   templateId: res.data.name, // 模版id
            //   sendDate: res.data.sendDate,
            //   time: res.data.name,
            //   time1: res.data.name,
            //   targetType: undefined,
            //   userTagId: [],
            //   userIds: undefined,
            //   specificUserType: undefined,
            // }
            // this.bigBoxStatusBefore = true;
          }
        }
      })
      if(type === 'view') this.bigBoxViewStatus = true;
    },
    disabledDate(time) {
      return time.getTime() < new Date(new Date().setHours(0, 0, 0, 0)).getTime();
    },
    editApiFn() {
      updateManage({
        id: this.selectDataInfo.id,
        sendDate: moment(this.editForm.sendDate).format('YYYY-MM-DD HH:mm:ss')
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '编辑成功',
            type: 'success'
          });
          this.resetForm('editForm');
          this.editBoxStatus = false;
          this.getTableData();
        }
      })
    },
    showBigBoxFn() {
      this.bigBoxStatus = true;
      this.getTemplateList();
      this.getUserRelList();
    },
    // 获取标签用户
    getUserRelList() {
      userRelList().then(res => {
        if (res.code === 200) {
          this.userTagList = res.data
        }
      })
    },
    // 自定义人群选择文件
    changeFile(event) {
      const XLSX = require('xlsx');
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0]; // 获取第一个工作表的名称
        const sheet = workbook.Sheets[sheetName]; // 获取工作表数据
        const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
        this.form2.userIds = jsonData.flat().join('\n')
      };
      reader.readAsArrayBuffer(file)
    },
    handleChangeRulesNumber(value, index) {

    },
    addRulesFn() { // 添加阶梯
      this.activityRulesArr.push({
        num: null,
        selectValue: null,
        rewardId: null,
      })
    },
    removeRulesFn(index) { // 删除阶梯
      this.activityRulesArr.splice(index, 1);
    },
    onEditSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if(formName === 'form2') {
          if (valid) {
            const timeCalibration = this.sendDataCalibration(this.form2.sendDate);
            if(timeCalibration) return this.$message({
              message: '不能小于当前时间',
              type: 'warning'
            });
            this.bigBoxLoading = true;
            this.$confirm('是否确认创建活动？')
              .then(_ => {
                this.addSmsApiFn()
              })
              .catch(_ => {
                this.bigBoxLoading = false;
              });
          } else {
            return false;
          }
        } else {
          if (valid) {
            const timeCalibration = this.sendDataCalibration(this.editForm.sendDate);
            if(timeCalibration) return this.$message({
              message: '不能小于当前时间',
              type: 'warning'
            });
            return this.editApiFn(); // 其他情况允许选择
          }
        }
      });
    },
    sendDataCalibration(times) {
      // 获取当前时间
      const now = new Date();
      // 获取时间的年月日时分秒
      const nowYear = now.getFullYear();
      const nowMonth = now.getMonth() + 1; // 月份是从0开始的，所以需要+1
      const nowDay = now.getDate();
      const nowHour = now.getHours();
      const nowMinute = now.getMinutes();
      const nowSecond = now.getSeconds();
      // 将时间转换为年月日时分秒格式，以便比较
      const time = new Date(times);
      const selectedYear = time.getFullYear();
      const selectedMonth = time.getMonth() + 1; // 月份是从0开始的，所以需要+1
      const selectedDay = time.getDate();
      const selectedHour = time.getHours();
      const selectedMinute = time.getMinutes();
      const selectedSecond = time.getSeconds();
      let goEditStatus = true;
      // 比较当前时间与选择的时间
      if (selectedYear < nowYear) {
        goEditStatus = true; // 如果选择的年份小于当前年份，则禁用
      } else if (selectedYear === nowYear && selectedMonth < nowMonth) {
        goEditStatus = true; // 如果选择的年份等于当前年份，但月份小于当前月份，则禁用
      } else if (selectedYear === nowYear && selectedMonth === nowMonth && selectedDay < nowDay) {
        goEditStatus = true; // 如果选择的年份和月份都等于当前年份和月份，但日期小于当前日期，则禁用
      } else if (selectedYear === nowYear && selectedMonth === nowMonth && selectedDay === nowDay && selectedHour < nowHour) {
        goEditStatus = true; // 如果年份、月份、日期都相等，但小时小于当前小时，则禁用
      } else if (selectedYear === nowYear && selectedMonth === nowMonth && selectedDay === nowDay && selectedHour === nowHour && selectedMinute < nowMinute) {
        goEditStatus = true; // 如果年份、月份、日期、小时都相等，但分钟小于当前分钟，则禁用
      } else if (selectedYear === nowYear && selectedMonth === nowMonth && selectedDay === nowDay && selectedHour === nowHour && selectedMinute === nowMinute && selectedSecond < nowSecond) {
        goEditStatus = true; // 如果年份、月份、日期、小时、分钟都相等，但秒数小于当前秒数，则禁用
      } else {
        goEditStatus = false;
      }
      return goEditStatus;
    },
    // 新增短信活动
    addSmsApiFn() {
      const params = { ...this.form2 };
      if(params.targetType !== '1') delete params.userTagId;
      if (params.targetType === '2') {
        params.userIds = params.userIds.split('\n');
      } else {
        delete params.userIds;
      }
      params.sendDate = moment(params.sendDate).format('YYYY-MM-DD HH:mm:ss');
      const timeObj = {
        time: params.time,
        time1: params.time1
      };
      delete params.time;
      delete params.time1;
      if(params.templateId == '2') {
        params.param = JSON.stringify(timeObj);
      }
      params.targetType = +params.targetType
      params.templateId = +params.templateId
      // console.log('params', params)
      // return
      addSms({
        ...params
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            message: '创建成功',
            type: 'success'
          });
          this.resetForm('form2');
          this.bigBoxStatus = false;
          this.getTableData();
        }
        this.bigBoxLoading = false;
      })
    }
  }
}
</script>
<style scoped lang="scss">
.invitation-filterhead {

}
.table-box {
  .add-activity {
    float: right;
    margin: 10px 0;
  }
  .table-switch {
    margin-right: 10px;
  }
}
  .bigbox-line {
    // border-bottom: 1px solid #dcdcdc;
    padding: 10px;
    .bigbox-lable {
      font-size: 14px;
      font-weight: bold;
    }
    .rules-list {
      display: flex;
      flex-direction: column;
      margin-bottom: 10px;
      .rules-item {
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 10px 0;
        .user-stairs {

        }
        .user-input {
          display: flex;
          align-items: center;
          margin: 0 10px;
          .el-input {
            flex: 1;
            margin-right: 5px;
          }
        }
        .user-select {
          display: flex;
          align-items: center;
          margin: 0 10px;
          .el-select {
            flex: 1;
            margin-right: 5px;
          }
        }
        .user-reward {

        }
      }
    }
    .rules-edit {
      color: #1890ff;
      font-weight: bold;
      cursor: pointer;
    }
    .go-file {
      width: 200px;
      min-height: 160px;
      border: 1px dashed #dcdcdc;
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;
      font-size: 12px;
      line-height: 16px;
      margin-top: 10px;
    }
    .file {
      width: 200px;
      height: auto;
      margin-top: 10px;
    }
  }
  .submint-btn {
    width: 100%;
    display: flex;
    justify-content: center;
  }
  .sms_moban_config {
    // display: flex;
    .el-form-item {
      display: inline-block;
    }
    .el-input {
      display: inline-block;
      width: 200px;
    }
  }
  .disable-edit {
    cursor: pointer;
    color: #dcdcdc;
  }
</style>
